const mongoose = require("../db");
const Schema = mongoose.Schema;

const followUpSchema = new Schema({
  leadId: { type: mongoose.Schema.Types.ObjectId, ref: 'Lead' },
  opportunityId: { type: mongoose.Schema.Types.ObjectId, ref: 'Opportunity' },
  content: { type: String, required: true },
  type: { 
    type: String, 
    enum: ['电话', '邮件', '面谈', '其他'], 
    default: '电话' 
  },
  nextFollowUp: { type: Date },
  createdBy: { type: mongoose.Schema.Types.ObjectId, ref: 'Admin' },
  createTime: { type: Date, default: Date.now }
});

// 创建索引
followUpSchema.index({ leadId: 1 });
followUpSchema.index({ opportunityId: 1 });
followUpSchema.index({ createdBy: 1 });
followUpSchema.index({ type: 1 });
followUpSchema.index({ nextFollowUp: 1 });
followUpSchema.index({ createTime: -1 });

// 验证至少有一个关联对象
followUpSchema.pre('save', function(next) {
  if (!this.leadId && !this.opportunityId) {
    const error = new Error('跟进记录必须关联线索或商机');
    return next(error);
  }
  next();
});

module.exports = mongoose.model("FollowUp", followUpSchema);